<template>
	<div class="user_box">
		<el-card>
			<!-- 搜索框 开始 -->
			<el-input 
				placeholder="请输入内容"
				clearable
				v-model.trim="reqParams.query">
				<el-button 
				slot="append" 
				icon="el-icon-search"
				@click="handleRearch">搜索</el-button>
			</el-input>
			<!-- 搜索框 结束 -->
			<el-button 
				type="primary" 
				class="search_btn"
				@click="handleAddUser">添加用户</el-button>
			<!-- 用户列表 开始 -->
			<el-table
					max-height="450"
			    :data="usersList"
			    border
					stripe
			    style="width: 100%">
					<el-table-column
						type="index"
						:index="1">
					</el-table-column>
			    <el-table-column
			      prop="username"
			      label="姓名"
			      width="180">
			    </el-table-column>
			    <el-table-column
			      prop="email"
			      label="邮箱"
			      width="180">
			    </el-table-column>
			    <el-table-column
			      prop="mobile"
			      label="电话">
			    </el-table-column>
					<el-table-column
					  prop="role_name"
					  label="角色">
					</el-table-column>
					<el-table-column
					  label="状态">
						<template slot-scope="scope">
							<el-switch
							  v-model="scope.row.mg_state"
							  active-color="#409EFF"
							  inactive-color="#DCDFE6"
								@change="handleStateChange(scope.row)">
							</el-switch>  
						</template>
					</el-table-column>
					<el-table-column
					  label="操作">
							<template slot-scope="scope">
								<el-tooltip
									class="item" effect="dark" 
									content="编辑" placement="top"
									:enterable="false">
									<el-button type="primary" icon="el-icon-edit" size="mini" 
										@click="handleEdit(scope.row)"></el-button>
								</el-tooltip>
								<el-tooltip
									class="item" effect="dark" 
									content="分配角色" placement="top"
									:enterable="false">
									<el-button type="warning" icon="el-icon-setting" size="mini"
										@click="handleSetRole(scope.row)"></el-button>
								</el-tooltip>
								<el-tooltip
									class="item" effect="dark" 
									content="删除" placement="top"
									:enterable="false">
									<el-button type="danger" icon="el-icon-delete" size="mini"
										@click="handleDel(scope.row)"></el-button>
								</el-tooltip>
							</template>
					</el-table-column>
			  </el-table>
				<!-- 用户列表 结束 -->
				<!-- 分页器 开始 -->
				<el-pagination
					:current-page="reqParams.pagenum"
					:page-sizes="[1, 3, 5, 10]"
					:page-size="reqParams.pagesize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					@size-change="handlePageSizeChange"
					@current-change="handlePageNumChange">
				</el-pagination>
				<!-- 分页器 开始 -->
		</el-card>
		
		<!-- 对话框 开始 -->
		<el-dialog 
			width="40%"
			:title="dialogTitles[curFormRef]" 
			:visible.sync="isDialogVisible"
			@close="handleDialogClose">
			
			<!-- 添加用户 开始 -->
			<el-form 
				ref="addUserFormRef" 
				label-width="80px" 
				:model="addUserForm" 
				:rules="rules"
				v-show="curFormRef === 'addUserFormRef'">
			  <el-form-item label="用户名" prop="username">
			    <el-input v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
			  </el-form-item>
			  <el-form-item label="密码" prop="password">
			    <el-input v-model="addUserForm.password" placeholder="请输入密码"></el-input>
			  </el-form-item>
				 <el-form-item label="邮箱" prop="email">
				   <el-input v-model="addUserForm.email" placeholder="请输入邮箱"></el-input>
				 </el-form-item>
				 <el-form-item label="手机号" prop="mobile">
				   <el-input v-model="addUserForm.mobile" placeholder="请输入手机号"></el-input>
				 </el-form-item>
			</el-form>
			<!-- 添加用户 结束 -->
			
			<!-- 编辑用户 开始 -->
			<el-form 
				ref="editFormRef" 
				label-width="80px" 
				:model="editUserForm" 
				:rules="rules"
				v-show="curFormRef === 'editFormRef'">
					<el-form-item label="用户名">
						<el-input v-model="editUserForm.username" :disabled="true"></el-input>
					</el-form-item>
					<el-form-item label="邮箱" prop="email">
						<el-input v-model="editUserForm.email" placeholder="请输入邮箱"></el-input>
					</el-form-item>
					<el-form-item label="手机号" prop="mobile">
						<el-input v-model="editUserForm.mobile" placeholder="请输入手机号"></el-input>
					</el-form-item>
			</el-form>
			<!-- 编辑用户 结束 -->
			
			<!-- 分配角色 开始-->
			<el-form ref="setRoleFormRef" :model="setRoleform" label-width="100px"
				label-position="left"
				v-show="curFormRef === 'setRoleFormRef'"
				class="setRoleForm">
				<el-form-item label="用户名:">
					<p class="username">{{setRoleform.username}}</p>
				</el-form-item>
				<el-form-item label="当前角色:">
					<p class="username">{{setRoleform.role_name}}</p>
				</el-form-item>
				<el-form-item label="分配新角色:" label-width="100px">
					<el-select v-model="selectedRoleId" placeholder="请选择">
						<el-option
							v-for="item in rolesList"
							:key="item.id"
							:label="item.roleName"
							:value="item.id"
							:disabled="item.roleName === setRoleform.role_name">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<!-- 分配角色 结束 -->
			
			<div slot="footer" class="dialog-footer">
				<el-button @click="isDialogVisible = false">取 消</el-button>
				<el-button 
					type="primary" 
					@click="handleConfirmed">确 定</el-button>
			</div>
		</el-dialog>
		<!-- 对话框 结束 -->
	</div>
</template>

<script>
	export default {
		name: 'User',
		data(){
			
			//邮箱验证规则
			var validateEmail = (rule, value, callback) => {
				//Email正则
				var pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				
				if(!pattern.test(value)){
					callback(new Error('请输入合法的邮箱！'))
				}
				callback()
			}
			
			//手机号验证规则
			var validateMobile = (rule, value, callback) => {
				//Email正则 
				var pattern = /^((\+|00)86)?1\d{10}$/;
				
				if(!pattern.test(value)){
					callback(new Error('请输入合法的手机号！'))
				}
				callback()
			}
			
			return {
				//请求参数
				reqParams: {
					query: '',
					pagenum: 1,
					pagesize: 1
				},
				//用户列表数据
				usersList: [],
				//角色列表数据
				rolesList: [],
				//选中的角色id
				selectedRoleId: '',
				//总条数
				total: 0,
				//对话框 显示标识
				isDialogVisible: false,
				//当前表单ref
				curFormRef: 'addUserFormRef',
				//对话框标题列表
				dialogTitles: {
					'addUserFormRef': '添加用户',
					'editFormRef': '编辑用户',
					'setRoleFormRef': '分配角色'
				},
				//添加用户 表单对象
				addUserForm: {
					username: '',
					password: '',
					email: '',
					mobile: ''
				},
				//编辑用户 表单对象
				editUserForm: {
					id: '',
					username: '',
					email: '',
					mobile: ''
				},
				//分配角色 表单对象
				setRoleform: {
					
				},
				//添加用户 表单验证规则
				rules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' },
						{ min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ min: 6, max: 11, message: '长度在 6 到 15 个字符', trigger: 'blur' },
					],
					email: [
						{ required: true, message: '请输入邮箱', trigger: 'blur' },
						{ validator: validateEmail, trigger: 'blur' }
					],
					mobile: [
						{ required: true, message: '请输入手机号', trigger: 'blur' },
						{ validator: validateMobile, trigger: 'blur' }
					]
				}
			}
		},
		created() {
			//请求用户列表数据
			this.getUsersList()
			
			//请求角色列表数据
			this.getRolesList()
		},
		methods: {
			async getUsersList(){
				const { data: res } = await this.$axios.get('/users', {
					params: this.reqParams
				})
				this.usersList = res.data.users
				this.total = res.data.total
			},
			//pagesize改变事件 
			handlePageSizeChange(val){
				this.reqParams.pagesize = val
				//pagesize改变，重新请求用户列表数据
				this.getUsersList()
			},
			//pagenum改变事件 
			handlePageNumChange(val){
				this.reqParams.pagenum = val
				//pagenum改变，重新请求用户列表数据
				this.getUsersList()
			},
			//搜索按钮 
			handleRearch(){
				this.getUsersList()
			},
			//对话框 确认按钮 
			handleConfirmed(){
				
				//分配角色时，如果没有选择新角色，则阻止提交
				if(this.curFormRef === 'setRoleFormRef'){
					if(!this.selectedRoleId){
						this.$message('请选择要分配的角色!')
						return
					}
				}
				
				this.$refs[this.curFormRef].validate(async (res, fail) => {
					if(res){
						//获取请求接口信息
						let reqInfo = this.getReqInfo()
						//console.log(reqInfo)
						
						//发起请求，提交数据
						const {data: res} = await this.$axios[reqInfo.method](reqInfo.path, reqInfo.data)
						
						//关闭对话框
						this.isDialogVisible = false
						
						//操作成功后的提示
						this.$message({
							message: reqInfo.Mes,
							type: reqInfo.MesType
						})
					}
				})
			},
			//对话框 关闭事件 
			handleDialogClose(){
				//移除验证结果，重置表单数据
				this.$refs[this.curFormRef].resetFields()
				
				//重置
				if(this.curFormRef === 'setRoleFormRef'){
					this.resetRoleForm()
				}
				
				//重新请求用户列表数据
				this.getUsersList()
			},
			//用户状态栏 开关改变事件 
			async handleStateChange(scope){
				//发起请求，提交数据
			  const {data: res} = await	this.$axios.put(`/users/${scope.id}/state/${scope.mg_state}`)
			
				this.$message({
					message: '修改用户状态成功。',
					type: 'success'
				})
			},
			//添加按钮 
			handleAddUser(){
				this.curFormRef = 'addUserFormRef'
				this.isDialogVisible = true
			},
			//编辑按钮 
			handleEdit(scope){
				//console.log(scope)
				this.curFormRef = 'editFormRef'
				this.isDialogVisible = true
				//深拷贝
				this.editUserForm = JSON.parse(JSON.stringify(scope))
			},  
			//分配角色按钮
			handleSetRole(scope){
				//console.log(scope)
				this.curFormRef = 'setRoleFormRef'
				this.isDialogVisible = true
				//深拷贝
				this.setRoleform = JSON.parse(JSON.stringify(scope))
			},
			//不同的表单，请求不同的接口
			getReqInfo(){
				let cbList = {
					//添加用户
					addUserFormRef: {
						method: 'post',
						path: '/users',
						data: this.addUserForm,
						Mes: '添加用户成功。',
						MesType: 'success'
					},
					//编辑用户
					editFormRef: {
						method: 'put',
						path: `/users/${this.editUserForm.id}`,
						data: {
							email: this.editUserForm.email,
							mobile: this.editUserForm.mobile
						},
						Mes: '修改用户成功。',
						MesType: 'success'
					},
					//分配角色
					setRoleFormRef: {
						method: 'put',
						path: `/users/${this.setRoleform.id}/role`,
						data: {
							rid: this.selectedRoleId
						},
						Mes: '分配角色成功。',
						MesType: 'success'
					}
				}
				return cbList[this.curFormRef]
			},
			//请求 角色列表数据
			async getRolesList(){
				const {data: res} = await this.$axios.get('/roles')
				this.rolesList = res.data
			},
			//分配角色 重置工作
			resetRoleForm(){
				this.selectedRoleId = ''
			},
			//删除按钮
			handleDel(scope){
				this.$confirm(`此操作将永久删除该用户：${scope.username}, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
				.then(async result => {
					const {data: res} = await this.$axios.delete(`/users/${scope.id}`)
					
					this.$message({
						message: '删除用户成功。',
						type: 'success'
					})
										
					//重新请求 用户列表数据
					this.getUsersList()
				})
				.catch(err => {
					this.$message('已取消删除。')
				})
			}
		}
	}
</script>

<style scoped="scoped" lang="less">
	.el-card.is-always-shadow, 
	.el-card.is-hover-shadow:focus, 
	.el-card.is-hover-shadow:hover {
		box-shadow: 0 1px 1px 0 rgba(0,0,0,0.1);
	}
	.el-input{
		width: 400px;
	}
	.search_btn{
		margin-left: 20px;
	}
	.el-table{
		margin: 20px 0;
		font-size: 12px;
	}
	.setRoleForm {
		.el-form-item {
			margin-bottom: 0;
		}
	}
</style>
